<template>
  <div class="flip-unit">
    <div class="digit" :class="{ flip: isFlipping }">
      <div class="top">{{ previousDigit }}</div> 
      <div class="bottom">{{ previousDigit }}</div>
      <div class="flip-top">{{ digit }}</div>
      <div class="flip-bottom">{{ digit }}</div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  digit: {
    type: Number,
    required: true
  }
})
const previousDigit = ref(props.digit)
const isFlipping = ref(false)

watch(() => props.digit, (newVal, oldVal) => {
if (newVal !== oldVal) {
  isFlipping.value = true
  setTimeout(() => {
    previousDigit.value = newVal
    isFlipping.value = false
  }, 600) // 动画时间需要与CSS匹配
}
})
</script>

<style lang="scss" scoped>
.flip-unit {
  perspective: 1000px;
  display: inline-block;
}

.digit {
  position: relative;
  width: 120px;
  height: 80px;
  font-size: 64px;
  text-align: center;
  line-height: 80px;
  color: white;
  background: #333;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
  &::before{
    content: "";
    position: absolute;
    top: 50%;
    left: 0;
    z-index: 1;
    width: 100%;
    height: 2px;
    background: #f0f0f0;
  }
  .top,.bottom,.flip-top,.flip-bottom{
    position: absolute;
    left: 0;
    width: 100%;
    height: 50%;
    overflow: hidden;
    backface-visibility: hidden;
    transition: transform 0.6s ease;
  }
  .top,.flip-top{
    background: skyblue;
    line-height: 80px;
    transform-origin: center bottom;
  }
  .bottom,.flip-bottom{
    background: skyblue;
    top: 50%;
    line-height: 0;
    transform-origin: center top;
  }
  .top {
    transform: rotateX(0deg);
  }
  .bottom {
    transform: rotateX(0deg);
  }
  .flip-top {
    top: 0;
    transform: rotateX(90deg);
  }
  .flip-bottom {
    transform: rotateX(-90deg);
  }
 
  &.flip {
    .top {
      transform: rotateX(-90deg);
    }
    .bottom {
      transform: rotateX(90deg);
    }
    .flip-top {
      transform: rotateX(0deg);
    }
    .flip-bottom {
      transform: rotateX(0deg);
    }
  }
}
</style>